import Mock from 'mockjs'
import config from './config'
import * as login from './modules/login'
import * as sysUser from './modules/sysUser'
const { baseURL, timeout } = config
Mock.setup({
    timeout
})

const openMock = true

mockAll([login, sysUser], openMock)

function mockAll(modules, isOpen = true) {
    for (const k in modules) {
        mock(modules[k], isOpen)
    }
}

function mock(mod, isOpen = true) {
    if (isOpen) {
        for (var key in mod) {
            ((res) => {
                if (res.isOpen !== false) {
                    let url = baseURL
                    if (!url.endsWith("/")) {
                        url += "/"
                    }

                    url = url + res.url
                    Mock.mock(new RegExp(url), res.method, (opts) => {
                        opts.data = opts.body ? JSON.parse(opts.body) : null
                        const resData = Mock.mock(typeof res.response === 'function' ? res.response(opts) : res.response)
                        console.log("%cmock拦截,请求: ", "color:blue", opts)
                        console.log("%cmock拦截,响应: ", "color:blue", resData)
                        return resData
                    })
                }
            })(mod[key]() || {})
        }
    }
}